import { Component } from 'react'
import { BrowserRouter as Router, withRouter } from 'react-router-dom'

let prevLocation, currLoation, currAction, unBlock, unListen;

// 该组件用于获取上下文 添加阻塞
class _GuardHelp extends Component {
    componentDidMount() {
        // this.props.history.block('阻塞')
        unBlock = this.props.history.block((location, action) => {
            prevLocation = this.props.location
            currLoation = location
            currAction = action
            return '阻塞'
        })
        // 添加一个监听器
        unListen = this.props.history.listen((...regs) => {
            this.props.onChange(this.props.location, ...regs, unListen)
        })
    }
    componentWillUnmount() { unBlock(); unListen(); }
    render = () => null
}
const GuardHelp = withRouter(_GuardHelp)

class RouteCuard extends Component {
    handleConfirmation = (msg, done) => {
        console.log(msg);
        this.props.onBeforeChange(prevLocation, currLoation, currAction, done, unBlock)
    }
    render() {
        return (
            <Router getUserConfirmation={this.handleConfirmation}>
                <GuardHelp onChange={this.props.onChange} />
                {this.props.children}
            </Router>
        )
    }
}

export default RouteCuard